package com.kfyang.manualgear.generator.impl.jdbc.orm;

import com.kfyang.manualgear.constant.TypeNameConstants;
import com.kfyang.manualgear.struct.EntityInfo;
import com.kfyang.manualgear.struct.FieldInfo;
import com.kfyang.manualgear.util.StringUtils;
import com.squareup.javapoet.MethodSpec;

import java.util.StringJoiner;

import static com.kfyang.manualgear.constant.Constants.*;
import static com.kfyang.manualgear.constant.StatementConstants.NEW_PARAMETER_LIST;
import static com.kfyang.manualgear.generator.impl.jdbc.constant.StatementConstants.*;
import static com.kfyang.manualgear.generator.impl.jdbc.constant.SqlConstants.*;

public class UpdateMethod extends AbstractMethod {

    protected UpdateMethod(MethodSpec.Builder methodBuilder, EntityInfo entityInfo, boolean forOne) {
        super(methodBuilder, entityInfo, forOne);
    }

    @Override
    protected void prepareParameters() {
        methodBuilder.addStatement(NEW_PARAMETER_LIST,
            TypeNameConstants.LIST_OBJECT_TYPE, TypeNameConstants.ARRAY_LIST_TYPE);

        for (FieldInfo fieldInfo : entityInfo.fieldInfos) {
            methodBuilder.addStatement(ADD_ENTITY_VALUE, StringUtils.toGetMethod(fieldInfo.field));
        }
        if (entityInfo.updateTimeInfo != null) {
            methodBuilder.addStatement(ADD_NEW_OBJECT, TypeNameConstants.DATE_TYPE);
        }
        methodBuilder.addStatement(ADD_ENTITY_VALUE, StringUtils.toGetMethod(entityInfo.idInfo.col));
    }

    @Override
    protected void prepareSql() {
        methodBuilder.addStatement(SQL_DEFINE + UPDATE_SQL +
                (entityInfo.deleteInfo == null ? EMPTY : AND + entityInfo.deleteInfo.col + EQUAL + NOT_DELETED) + QUOTA,
            entityInfo.tableName, updateColumn(), entityInfo.idInfo.col);
    }

    @Override
    public void addReturn() {
        methodBuilder.addStatement(RETURN_MODIFY_RESULT);

    }

    /**
     * 更新列表
     * @return 更新列表
     */
    private String updateColumn() {
        StringJoiner columnJoiner = new StringJoiner(COMMA);
        for (FieldInfo fieldInfo : entityInfo.fieldInfos) {
            columnJoiner.add(fieldInfo.col + EQUAL + PLACE_HOLDER);
        }
        if (entityInfo.updateTimeInfo != null) {
            columnJoiner.add(entityInfo.updateTimeInfo.col + EQUAL + PLACE_HOLDER);
        }
        return columnJoiner.toString();
    }
}
